<template>
  <div class="tool-detail">
    <el-skeleton v-if="loading" :rows="10" animated />

    <div v-else-if="currentTool" class="tool-content" v-loading="refreshingParams">
      <div class="tool-header">
        <div class="tool-info">
          <div class="tool-icon">
            <img v-if="currentTool.icon" :src="currentTool.icon" :alt="currentTool.name" />
            <el-icon v-else><Tools /></el-icon>
          </div>
          <div>
            <h1>{{ currentTool.name }}</h1>
            <p class="category">分类：{{ currentTool.category.name }}</p>
          </div>
        </div>
        <div class="action-buttons">
          <el-button
            v-if="isSubscribed"
            type="danger"
            @click="handleUnsubscribe"
          >
            取消开通
          </el-button>
          <el-button
            v-else
            type="primary"
            @click="handleSubscribe"
          >
            立即开通
          </el-button>
        </div>
      </div>

      <div class="tool-description">
        <h2>工具描述</h2>
        <p>{{ currentTool.description || '暂无描述' }}</p>
      </div>

      <div class="tool-usage">
        <el-tabs v-model="activeTab">
          <el-tab-pane :label="currentTool.english_name" name="tool">
            <div class="parameter-form">
              <el-collapse v-model="activeNames">
                <el-collapse-item title="参数设置" name="parameters">
                  <template v-if="currentTool?.mcp_config?.mcpServers">
                    <el-alert
                      type="info"
                      :closable="false"
                      show-icon
                    >
                      参数从MCP服务获取：{{ getMcpServerUrl() }}
                      <el-button 
                        type="primary" 
                        size="small" 
                        style="margin-left: 10px"
                        @click="refreshToolParams"
                      >
                        刷新参数
                      </el-button>
                    </el-alert>
                  </template>
                  
                  <!-- MCP工具选择 -->
                  <div v-if="mcpTools.length > 0" class="mcp-tool-select">
                    <el-form-item label="选择MCP工具">
                      <el-select v-model="selectedMcpTool" placeholder="请选择MCP工具" @change="handleMcpToolChange">
                        <el-option
                          v-for="tool in mcpTools"
                          :key="tool.name"
                          :label="tool.name"
                          :value="tool.name"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>

                  <!-- 参数表单 -->
                  <div v-if="currentMcpToolParams && currentMcpToolParams.properties">
                    <el-form :model="parameters" label-position="top">
                      <template v-for="(prop, key) in currentMcpToolParams.properties" :key="key">
                        <el-form-item
                          :label="prop.description || key"
                          :required="isRequired(key)"
                        >
                          <!-- 字符串输入 -->
                          <el-input
                            v-if="prop.type === 'string' && !prop.enum"
                            v-model="parameters[key]"
                            :placeholder="`请输入${key}`"
                          ></el-input>
                          
                          <!-- 枚举选择 -->
                          <el-select
                            v-else-if="prop.type === 'string' && prop.enum"
                            v-model="parameters[key]"
                            :placeholder="`请选择${key}`"
                            style="width: 100%"
                          >
                            <el-option
                              v-for="item in prop.enum"
                              :key="item"
                              :label="item"
                              :value="item"
                            ></el-option>
                          </el-select>
                          
                          <!-- 数字输入 -->
                          <el-input-number
                            v-else-if="prop.type === 'integer' || prop.type === 'number'"
                            v-model="parameters[key]"
                            :min="prop.minimum"
                            :max="prop.maximum"
                            style="width: 100%"
                          ></el-input-number>
                          
                          <!-- 布尔值 -->
                          <el-switch
                            v-else-if="prop.type === 'boolean'"
                            v-model="parameters[key]"
                          ></el-switch>
                          
                          <!-- 默认文本输入 -->
                          <el-input
                            v-else
                            v-model="parameters[key]"
                            :placeholder="`请输入${key}`"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-form>
                  </div>
                  <div v-else class="no-parameters">
                    <p>该工具没有可配置的参数</p>
                  </div>
                </el-collapse-item>
              </el-collapse>
              
              <div class="form-actions">
                <el-button type="primary" @click="handleRunTool" :loading="runningTool">运行</el-button>
              </div>
            </div>
            
            <!-- 结果展示 -->
            <div v-if="result" class="result-section">
              <h3>运行结果</h3>
              <el-card shadow="never">
                <pre class="result-content">{{ result }}</pre>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <div v-else class="not-found">
      <el-empty description="工具不存在或已被删除" />
      <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
    </div>
    
    <!-- 订阅确认对话框 -->
    <el-dialog
      v-model="subscribeDialogVisible"
      title="开通确认"
      width="30%"
    >
      <span>确认要开通「{{ currentTool?.name }}」吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="subscribeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSubscribe" :loading="subscribing">
            确认开通
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 取消订阅确认对话框 -->
    <el-dialog
      v-model="unsubscribeDialogVisible"
      title="取消开通确认"
      width="30%"
    >
      <span>确认要取消开通「{{ currentTool?.name }}」吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="unsubscribeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmUnsubscribe" :loading="unsubscribing">
            确认取消
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { Tools } from '@element-plus/icons-vue'
import { ElMessage, ElAlert } from 'element-plus'
import { nextTick } from 'vue'

export default {
  name: 'ToolDetail',
  components: {
    Tools,
    ElAlert
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      activeTab: 'tool',
      activeNames: ['parameters'],
      parameters: {},
      result: null,
      runningTool: false,
      refreshingParams: false,
      subscribeDialogVisible: false,
      unsubscribeDialogVisible: false,
      subscribing: false,
      unsubscribing: false,
      currentUserId: 1,
      loading: true,
      initialized: false,
      mcpTools: [],
      selectedMcpTool: null,
      currentMcpToolParams: null,
      currentToolId: null
    }
  },
  computed: {
    ...mapState(['currentTool', 'error']),
    ...mapGetters(['isToolSubscribed']),
    
    isSubscribed() {
      return this.isToolSubscribed(this.id, this.currentUserId)
    }
  },
  watch: {
    '$route.params.id': {
      immediate: true,
      handler(newId) {
        console.log('Route ID changed:', newId)
        if (newId) {
          this.currentToolId = parseInt(newId, 10)
          console.log('Set currentToolId to:', this.currentToolId)
          this.initializeComponent()
        }
      }
    }
  },
  mounted() {
    console.log('Component mounted, route params:', this.$route.params)
    console.log('Component mounted, props:', this.id)
    this.currentToolId = parseInt(this.$route.params.id, 10)
    console.log('Set currentToolId in mounted:', this.currentToolId)
    this.initializeComponent()
  },
  methods: {
    ...mapActions(['fetchTool', 'fetchToolParams', 'runTool', 'fetchUserSubscriptions', 'subscribeToTool', 'unsubscribeFromTool']),
    
    async initializeComponent() {
      try {
        this.loading = true
        const toolId = this.currentToolId
        console.log('Initializing with tool ID:', toolId)
        if (!toolId) {
          throw new Error('工具ID无效')
        }
        await this.loadData()
      } catch (error) {
        console.error('Error initializing component:', error)
        ElMessage.error('加载工具详情失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadData() {
      try {
        const toolId = this.currentToolId
        console.log('Loading data for tool ID:', toolId)
        if (!toolId) {
          throw new Error('工具ID无效')
        }
        await this.fetchTool(toolId)
        const paramsResponse = await this.fetchToolParams(toolId).catch(error => {
          console.warn('无法从MCP服务获取参数，使用工具预设参数', error)
        })
        
        // 处理MCP工具参数
        if (paramsResponse?.parameters_schema) {
          this.mcpTools = Object.entries(paramsResponse.parameters_schema).map(([name, schema]) => ({
            name,
            schema
          }))
          
          if (this.mcpTools.length > 0) {
            this.selectedMcpTool = this.mcpTools[0].name
            this.handleMcpToolChange(this.selectedMcpTool)
          }
        }
        
        await this.fetchUserSubscriptions(this.currentUserId)
      } catch (error) {
        console.error('Error loading tool:', error)
        throw error
      }
    },
    
    handleMcpToolChange(toolName) {
      console.log('Changing MCP tool to:', toolName)
      const tool = this.mcpTools.find(t => t.name === toolName)
      if (tool) {
        this.currentMcpToolParams = tool.schema
        // 重置参数
        this.parameters = {}
        if (tool.schema.properties) {
          Object.entries(tool.schema.properties).forEach(([key, prop]) => {
            // 设置默认值
            if (prop.default !== undefined) {
              this.parameters[key] = prop.default
            } else if (prop.type === 'boolean') {
              this.parameters[key] = false
            } else if (prop.type === 'integer' || prop.type === 'number') {
              this.parameters[key] = 0
            } else {
              this.parameters[key] = ''
            }
          })
        }
        console.log('Updated parameters:', this.parameters)
      }
    },
    
    isRequired(key) {
      return this.currentMcpToolParams?.required?.includes(key) || false
    },
    
    async handleRunTool() {
      // 验证工具ID
      const toolId = this.currentToolId
      console.log('Running tool with ID:', toolId)
      if (!toolId || isNaN(toolId)) {
        ElMessage.error('工具ID无效')
        return
      }

      // 验证是否选择了MCP工具
      if (!this.selectedMcpTool) {
        ElMessage.warning('请选择要运行的MCP工具')
        return
      }

      // 验证参数
      if (!this.validateParameters()) {
        ElMessage.warning('请填写所有必填参数')
        return
      }

      // 获取当前选中的MCP工具配置
      const currentTool = this.mcpTools.find(t => t.name === this.selectedMcpTool)
      if (!currentTool) {
        ElMessage.error('未找到选中的MCP工具配置')
        return
      }

      this.runningTool = true
      this.result = '正在执行...'
      
      try {
        // 构建请求参数
        const requestBody = {
          parameters: {
            name: this.selectedMcpTool,
            ...this.parameters
          }
        }

        console.log('执行MCP工具:', this.selectedMcpTool)
        console.log('工具ID:', toolId)
        console.log('请求体:', requestBody)

        const response = await fetch(`/api/v1/tools/${toolId}/run`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(requestBody)
        })

        if (!response.ok) {
          const errorData = await response.json()
          const errorMessage = errorData.detail?.[0]?.msg || errorData.detail || `HTTP error! status: ${response.status}`
          throw new Error(errorMessage)
        }

        const data = await response.json()
        if (data.error) {
          this.result = `错误：${data.error}`
          ElMessage.error(data.error)
        } else {
          this.result = JSON.stringify(data.result, null, 2)
          ElMessage.success('工具执行成功')
        }
      } catch (error) {
        this.result = `执行失败：${error.message}`
        ElMessage.error('工具运行失败')
        console.error('Error running tool:', error)
      } finally {
        this.runningTool = false
      }
    },
    
    validateParameters() {
      if (!this.currentMcpToolParams) {
        console.warn('No current MCP tool parameters found')
        return false
      }
      
      const { required = [] } = this.currentMcpToolParams
      console.log('Required parameters:', required)
      console.log('Current parameters:', this.parameters)
      
      const missingParams = required.filter(key => {
        const value = this.parameters[key]
        const isEmpty = value === null || value === undefined || value === ''
        console.log(`Checking parameter ${key}:`, { value, isEmpty })
        return isEmpty
      })

      if (missingParams.length > 0) {
        const missingParamNames = missingParams.map(key => {
          const prop = this.currentMcpToolParams.properties[key]
          return prop?.description || key
        })
        ElMessage.warning(`请填写必填参数: ${missingParamNames.join(', ')}`)
        return false
      }

      return true
    },
    
    getMcpServerUrl() {
      const servers = this.currentTool?.mcp_config?.mcpServers
      if (!servers) return '未配置'
      
      const firstServer = Object.values(servers)[0]
      return firstServer?.url || '未配置URL'
    },
    
    async refreshToolParams() {
      this.refreshingParams = true
      try {
        await this.fetchToolParams(this.id)
        await nextTick()
        
        if (this.currentTool?.parameters_schema?.properties) {
          const params = {}
          Object.entries(this.currentTool.parameters_schema.properties).forEach(([key, prop]) => {
            params[key] = prop.default !== undefined ? prop.default : null
          })
          this.parameters = params
        }
        
        ElMessage.success('参数刷新成功')
      } catch (error) {
        ElMessage.error('刷新参数失败')
        console.error('Error refreshing tool parameters:', error)
      } finally {
        this.refreshingParams = false
      }
    },
    
    handleSubscribe() {
      this.subscribeDialogVisible = true
    },
    
    async confirmSubscribe() {
      this.subscribing = true
      try {
        await this.subscribeToTool({
          userId: this.currentUserId,
          toolId: parseInt(this.id)
        })
        ElMessage.success('工具开通成功')
        this.subscribeDialogVisible = false
      } catch (error) {
        ElMessage.error('工具开通失败')
        console.error('Error subscribing to tool:', error)
      } finally {
        this.subscribing = false
      }
    },
    
    handleUnsubscribe() {
      this.unsubscribeDialogVisible = true
    },
    
    async confirmUnsubscribe() {
      this.unsubscribing = true
      try {
        await this.unsubscribeFromTool({
          userId: this.currentUserId,
          toolId: parseInt(this.id)
        })
        ElMessage.success('已取消开通')
        this.unsubscribeDialogVisible = false
      } catch (error) {
        ElMessage.error('取消开通失败')
        console.error('Error unsubscribing from tool:', error)
      } finally {
        this.unsubscribing = false
      }
    }
  }
}
</script>

<style scoped>
.tool-detail {
  max-width: 1000px;
  margin: 0 auto;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.tool-info {
  display: flex;
  align-items: center;
}

.tool-icon {
  margin-right: 20px;
}

.tool-icon img {
  width: 64px;
  height: 64px;
  object-fit: contain;
}

.tool-icon .el-icon {
  font-size: 64px;
  color: #409EFF;
}

.tool-info h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.category {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.tool-description {
  margin-bottom: 30px;
}

.tool-description h2 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 15px;
}

.tool-description p {
  color: #606266;
  line-height: 1.6;
}

.parameter-form {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}

.result-section {
  margin-top: 30px;
}

.result-section h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
}

.result-content {
  white-space: pre-wrap;
  font-family: monospace;
  font-size: 14px;
  color: #606266;
}

.no-parameters {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.not-found {
  text-align: center;
  padding: 40px 0;
}

.mcp-tool-select {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style> 